#include <iostream>
#include <pcap.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>

// Ethernet header structure
struct ethhdr {
    u_char dest[6];
    u_char source[6];
    u_short type;
};

// Function to process captured packets
void packetHandler(u_char *userData, const struct pcap_pkthdr *pkthdr, const u_char *packetData)
{
    struct ethhdr *ethernetHeader;
    struct ip *ipHeader;
    struct tcphdr *tcpHeader;
    const u_char *payload;

    ethernetHeader = (struct ethhdr *)packetData;
    if (ntohs(ethernetHeader->type) == 0x0800) { // IPv4 packet
        ipHeader = (struct ip *)(packetData + sizeof(struct ethhdr));
        if (ipHeader->ip_p == IPPROTO_TCP) { // TCP packet
            tcpHeader = (struct tcphdr *)(packetData + sizeof(struct ethhdr) + ipHeader->ip_hl * 4);
            payload = packetData + sizeof(struct ethhdr) + ipHeader->ip_hl * 4 + tcpHeader->th_off * 4;

            // Check if the packet contains SMTPS data (port 465)
            if (ntohs(tcpHeader->th_dport) == 465) {
                // Check if the packet is part of the SMTPS handshake
                if (pkthdr->len > sizeof(struct ethhdr) + ipHeader->ip_hl * 4 + tcpHeader->th_off * 4) {
                    std::cout << "SMTPS Sender: " << payload << std::endl;
                }
            }
        }
    }
}

int main()
{
    pcap_t *handle;
    char errbuf[PCAP_ERRBUF_SIZE];

    // Open the network device for packet capture
    handle = pcap_open_live("eno1", BUFSIZ, 1, 1000, errbuf); // Replace "eth0" with your network interface

    // Set a filter to capture only SMTPS traffic (port 465)
    struct bpf_program fp;
    char filter[] = "tcp port 465";
    pcap_compile(handle, &fp, filter, 0, PCAP_NETMASK_UNKNOWN);
    pcap_setfilter(handle, &fp);

    // Start capturing packets
    pcap_loop(handle, 0, packetHandler, NULL);

    // Close the packet capture handle
    pcap_close(handle);

    return 0;
}
